package http

import (
	"context"
	"im/lib/dao"
	"im/models"
	"im/servers/kafka"
	"im/servers/task"
	"log"
	"time"
)

func SendUserMessage(ctx context.Context, appID uint32, userID string, msgID, message string) (bool, error) {
	//第一步：将消息存储
	info := &models.ImUserMessage{
		AppId:          string(appID),
		UserId:         userID,
		MessageId:      msgID,
		MessageContent: message,
		SendTime:       time.Now(),
		IsRead:         true,
	}

	err := dao.CreateUserMessage(info)
	if err != nil {
		log.Println("dao.CreateUserMessage 操作失败,err:", err)
		//放到全局队列重新发送
		task.TaskQ.AddTask(&models.FailTask{
			ActionType: "im",
			Data:       info,
		})
		return false, err
	}
	//第二步A：异步将消息推送给kafka
	go func() {
		kafkaMsg := &models.CustomKafkaMsg{
			ActionType: "im",
			AppId:      appID,
			MsgId:      msgID,
			UserId:     userID,
			Data:       message,
			Timestamp:  time.Now(),
		}
		kafka.IMProduce.Send(ctx, kafkaMsg)
	}()
	return true, nil
}
